/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Funcionario.Pedido;

import Controle.Controlador;
import Modelo.Pizza;
import Modelo.Sabor;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Eder
 */
public class EditarPizza extends javax.swing.JFrame {

    DefaultTableModel modelo1;
    DefaultTableModel modelo2;
    TableRowSorter sorter;
    int numSabRestantes;
    EditarPedido np;
    Pizza pizza = new Pizza();
    ArrayList<Sabor> sabores;
    RowFilter<Object, Object> filtro1 = null;
    RowFilter<Object, Object> filtro2 = null;
    ArrayList<RowFilter<Object, Object>> andFilters = new ArrayList<>();
    Integer codPizzaPedido;
    Integer codigoPedido;
    /**
     * Creates new form EditarPizza
     */
    public EditarPizza() {
        initComponents();
    }

    public EditarPizza(EditarPedido np, Integer codigoPedido) {
        initComponents();
        this.np = np;
        this.codigoPedido = codigoPedido;
        modelo1 = (DefaultTableModel) jtabelaSaboresDisp.getModel();
        modelo2 = (DefaultTableModel) jtabelaPizzaPedido.getModel();
        sorter = new TableRowSorter(modelo1);
        jScrollPane1.getViewport().setBackground(Color.WHITE);
        jScrollPane2.getViewport().setBackground(Color.WHITE);
        andFilters.add(filtro1);
        andFilters.add(filtro2);
        //jquantidadeTF.setText("1");
        jtabelaSaboresDisp.getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getColumnModel().getColumn( 0 ).setMinWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 0 ).setMinWidth( 0 );
        jtabelaSaboresDisp.getColumnModel().getColumn( 3 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getColumnModel().getColumn( 3 ).setMinWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 3 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 3 ).setMinWidth( 0 );
        
        sabores = imprimeDadosTabelas(carregarDadosBD());
        jgrandeRBActionPerformed(null);
    }

    public EditarPizza(EditarPedido np, Integer codPizzaPedido, Integer codigoPedido) {
        initComponents();
        this.np = np;
        this.codPizzaPedido = codPizzaPedido;
        this.codigoPedido = codigoPedido;
        modelo1 = (DefaultTableModel) jtabelaSaboresDisp.getModel();
        modelo2 = (DefaultTableModel) jtabelaPizzaPedido.getModel();
        sorter = new TableRowSorter(modelo1);
        jScrollPane1.getViewport().setBackground(Color.WHITE);
        jScrollPane2.getViewport().setBackground(Color.WHITE);
        andFilters.add(filtro1);
        andFilters.add(filtro2);
        //jquantidadeTF.setText("1");
        jtabelaSaboresDisp.getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getColumnModel().getColumn( 0 ).setMinWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 0 ).setMinWidth( 0 );
        jtabelaSaboresDisp.getColumnModel().getColumn( 3 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getColumnModel().getColumn( 3 ).setMinWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 3 ).setMaxWidth( 0 );  
        jtabelaSaboresDisp.getTableHeader().getColumnModel().getColumn( 3 ).setMinWidth( 0 );

        sabores = imprimeDadosTabelas(carregarDadosBD());
        pizza = Controlador.carregarPizza_BD(codPizzaPedido);
        
        if (pizza.getTamanhoPizza().equals("Pequena")) {
            jpequenaRBActionPerformed(null);
        }
        if (pizza.getTamanhoPizza().equals("Media")) {
            jmediaRBActionPerformed(null);
        }
        if (pizza.getTamanhoPizza().equals("Grande")) {
            jgrandeRBActionPerformed(null);
        }
        if (pizza.getTamanhoPizza().equals("Gigante")) {
            jgiganteRBActionPerformed(null);
        }
        
        numSabRestantes -= pizza.getSabores().size();
        imprimeDadosTabelaPizzaPedido();
    }

    private void setDadosVisao(Pizza ap) {
        for (int i = 0; i < ap.getSabores().size(); i++) {
        }

    }

    private ArrayList<Sabor> carregarDadosBD() {
        ArrayList<Sabor> sab = new ArrayList<>();
        if (Controlador.carregarDadosBD_Sabores(sab)) {
            return sab;
        }
        return null;
    }

    private ArrayList<Sabor> imprimeDadosTabelas(ArrayList<Sabor> sabores) {
        // Adiciona uma nova linha em branco no modelo1  
        int linhaTabela = 0;

        //jTtabelaRP.setRowSorter(null); // desabilita o filtro

        for (int i = 0; i < sabores.size(); i++) {
            try {
                if (jtabelaSaboresDisp.getRowCount() <= linhaTabela) {
                    modelo1.addRow(new String[]{"", ""});
                }
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getCodigo(), linhaTabela, 0);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getNome(), linhaTabela, 1);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getIngredientes(), linhaTabela, 2);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getCategoria().getCodigo(), linhaTabela, 3);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getCategoria().getNome(), linhaTabela, 4);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getCategoria().getTamanho(), linhaTabela, 5);
                jtabelaSaboresDisp.setValueAt(sabores.get(i).getCategoria().getValor(), linhaTabela, 6);
            } catch (Exception ex) {
                System.out.println("Erro ao imprimir os dados na tabela\n" + ex.getMessage());
            }

            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        jfiltroTFKeyReleased(null);

        return sabores;
    }

    public void atualizaTabela() {
        sabores = imprimeDadosTabelas(carregarDadosBD());
    }

    public void removeLinhasInutilizadas(int linhaTabela) {
        for (int i = linhaTabela; i < jtabelaSaboresDisp.getRowCount(); i++) {
            modelo1.removeRow(i);
        }
    }

    public Sabor getSaborSelecionado(int cod, int cod_categ) {
        for (int i = 0; i < sabores.size(); i++) {
            if (sabores.get(i).getCodigo() == cod && sabores.get(i).getCategoria().getCodigo() == cod_categ) {
                return sabores.get(i);
            }
        }

        return null;
    }

    private void imprimeDadosTabelaPizzaPedido() {
        // Adiciona uma nova linha em branco no modelo1  
        int linhaTabela = 0;
        float valorTotal = 0;

        for (int i = 0; i < pizza.getSabores().size(); i++) {
            try {
                if (jtabelaPizzaPedido.getRowCount() <= linhaTabela) {
                    modelo2.addRow(new String[]{"", ""});
                }
                jtabelaPizzaPedido.setValueAt(pizza.getSabores().get(i).getCodigo(), linhaTabela, 0);
                jtabelaPizzaPedido.setValueAt(pizza.getSabores().get(i).getNome(), linhaTabela, 1);
                jtabelaPizzaPedido.setValueAt(pizza.getSabores().get(i).getCategoria().getNome(), linhaTabela, 2);
                jtabelaPizzaPedido.setValueAt(pizza.getSabores().get(i).getCategoria().getValor(), linhaTabela, 3);
                float valorCategoria = Float.parseFloat(jtabelaPizzaPedido.getValueAt(linhaTabela, 3).toString());
                if (valorCategoria > valorTotal) {
                    valorTotal = valorCategoria;
                }

            } catch (Exception ex) {
                System.out.println("Erro ao imprimir os dados na tabela\n" + ex.getMessage());
            }

            linhaTabela++;
        }
        jsaboresRestantesTF.setText("" + numSabRestantes);
        jvalorTF.setText("" + valorTotal);
    }

    public void atualizaTabelaPizzaPedido() {
        imprimeDadosTabelaPizzaPedido();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator3 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jvalorTF = new javax.swing.JTextField();
        jremoverSaborB = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jpequenaRB = new javax.swing.JRadioButton();
        jgiganteRB = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jadicionarSaborB = new javax.swing.JButton();
        jsaboresRestantesTF = new javax.swing.JTextField();
        jmediaRB = new javax.swing.JRadioButton();
        jSeparator1 = new javax.swing.JSeparator();
        jconcluirB = new javax.swing.JButton();
        jgrandeRB = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtabelaSaboresDisp = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtabelaPizzaPedido = new javax.swing.JTable();
        jfiltroTF = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jcancelarB = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Adicionar PIZZA");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Valor:");

        jvalorTF.setEditable(false);
        jvalorTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jvalorTFActionPerformed(evt);
            }
        });

        jremoverSaborB.setText("Remover Sabor");
        jremoverSaborB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jremoverSaborBActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Sabores Restantes:");

        jpequenaRB.setText("Pequena");
        jpequenaRB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpequenaRBActionPerformed(evt);
            }
        });

        jgiganteRB.setText("Gigante");
        jgiganteRB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jgiganteRBActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Tamanho:");

        jadicionarSaborB.setText("Adicionar Sabor");
        jadicionarSaborB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jadicionarSaborBActionPerformed(evt);
            }
        });

        jsaboresRestantesTF.setEditable(false);

        jmediaRB.setText("Média");
        jmediaRB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmediaRBActionPerformed(evt);
            }
        });

        jconcluirB.setText("Concluir");
        jconcluirB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jconcluirBActionPerformed(evt);
            }
        });

        jgrandeRB.setText("Grande");
        jgrandeRB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jgrandeRBActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Pizza Pedido");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Sabores Disponíveis:");

        jtabelaSaboresDisp.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Sabor", "Descrição", "Cod_categ", "Categoria", "Tamanho", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtabelaSaboresDisp);

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jtabelaPizzaPedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Sabor", "Categoria", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtabelaPizzaPedido);

        jfiltroTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jfiltroTFKeyReleased(evt);
            }
        });

        jLabel4.setText("Filtro");

        jcancelarB.setText("Cancelar");
        jcancelarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcancelarBActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(274, 274, 274)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jvalorTF, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jSeparator1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jpequenaRB, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jmediaRB, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jgrandeRB, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jgiganteRB))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(127, 127, 127)
                                .addComponent(jLabel5))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jsaboresRestantesTF, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jremoverSaborB))
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel6)
                                .addGap(129, 129, 129))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jfiltroTF)
                                .addGap(18, 18, 18)
                                .addComponent(jadicionarSaborB))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jcancelarB)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jconcluirB, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jcancelarB, jconcluirB});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jfiltroTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jadicionarSaborB)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jpequenaRB)
                            .addComponent(jmediaRB)
                            .addComponent(jgrandeRB)
                            .addComponent(jgiganteRB)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jsaboresRestantesTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jremoverSaborB, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 140, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jvalorTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(3, 3, 3)))
                .addGap(3, 3, 3)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jconcluirB)
                    .addComponent(jcancelarB))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-904)/2, (screenSize.height-440)/2, 904, 440);
    }// </editor-fold>//GEN-END:initComponents

    private void jvalorTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jvalorTFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jvalorTFActionPerformed

    private void jfiltroTFKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jfiltroTFKeyReleased
        // Filtro
        List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);

        filtro2 = RowFilter.regexFilter(jfiltroTF.getText().toUpperCase());
        if (filtro1 != null) {
            filters.add(filtro1);
        }
        if (filtro2 != null) {//||"".equals(jfiltroTF.getText())){
            filters.add(filtro2);
        }
        if (filtro1 != null || filtro2 != null) {
            sorter.setRowFilter(RowFilter.andFilter(filters));
            jtabelaSaboresDisp.setRowSorter(sorter);
        }

    }//GEN-LAST:event_jfiltroTFKeyReleased

    public String getTamanhoSelecionado(){
        if (jpequenaRB.isSelected()){
            return "Pequena";
        }
        if (jmediaRB.isSelected()){
            return "Media";
        }
        if (jgrandeRB.isSelected()){
            return "Grande";
        }
        if (jgiganteRB.isSelected()){
            return "Gigante";
        }
        return null;
    }
    
    public boolean validarAddSabor() {
        try {
            if (!jpequenaRB.isSelected() && !jmediaRB.isSelected() && !jgrandeRB.isSelected() && !jgiganteRB.isSelected()) {
                throw new Exception("Selecione o tamanho da Pizza!");
            }
            
            if (jpequenaRB.isSelected()){
                if(!ValidarTamanhoSaboresPizza("Pequena")){
                    throw new Exception("Existem Tamanho diferentes entre os Sabores da Pizza!");
                }
            }
            if (jmediaRB.isSelected()){
                if(!ValidarTamanhoSaboresPizza("Media")){
                    throw new Exception("Existem Tamanho diferentes entre os Sabores da Pizza!");
                }
            }
            if (jgrandeRB.isSelected()){
                if(!ValidarTamanhoSaboresPizza("Grande")){
                    throw new Exception("Existem Tamanho diferentes entre os Sabores da Pizza!");
                }
            }
            if (jgiganteRB.isSelected()){
                if(!ValidarTamanhoSaboresPizza("Gigante")){
                    throw new Exception("Existem Tamanho diferentes entre os Sabores da Pizza!");
                }
            }
            int sabRestantes = Integer.parseInt(jsaboresRestantesTF.getText());
            if (sabRestantes <= 0) {
                throw new Exception("Não é possivel adicionar mais sabores!");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Erro! " + e.getMessage(), "Erro!", 2);
            return false;
        }
        return true;
    }
    private void jadicionarSaborBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jadicionarSaborBActionPerformed
        // Botão Adicionar Sabor
        if (validarAddSabor()) {
            try {
                //jtabelaSaboresDisp.setRowSorter(null); // desabilita o filtro
                int linha = jtabelaSaboresDisp.getSelectedRow();

                if (linha == -1) {
                    throw new Exception("Selecione a linha do Sabor desejado");
                }

                int cod = Integer.parseInt(jtabelaSaboresDisp.getValueAt(linha, 0).toString());
                int cod_categ = Integer.parseInt(jtabelaSaboresDisp.getValueAt(linha, 3).toString());
                pizza.getSabores().add(getSaborSelecionado(cod, cod_categ));
                imprimeDadosTabelaPizzaPedido();

                numSabRestantes--;
                jsaboresRestantesTF.setText("" + (numSabRestantes));
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "ERRO ADD PIZZA "+e.getMessage());
            }
        }
        //jfiltroTFKeyReleased(null);
    }//GEN-LAST:event_jadicionarSaborBActionPerformed

    private void jremoverSaborBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jremoverSaborBActionPerformed
        // Botão Remover Sabor
        try {
            int linha = jtabelaPizzaPedido.getSelectedRow();
            if (linha != -1) {
                pizza.getSabores().remove(linha);
                modelo2.removeRow(linha);
                numSabRestantes++;

                atualizaTabelaPizzaPedido();
            } else {
                throw new Exception("Selecione a linha do Sabor desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jremoverSaborBActionPerformed

    private void jconcluirBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jconcluirBActionPerformed
        // Botão Concluir:
        try {
            
            int numlinha = jtabelaPizzaPedido.getRowCount();
            if (numlinha >= 0 && pizza.getSabores().size() >0) {
                if(!ValidarTamanhoSaboresPizza(getTamanhoSelecionado())){
                    throw new Exception("O Tamanho selecionado para a Pizza é diferentes dos seus Sabores!");
                }
                if(codPizzaPedido ==null){
                    pizza.setCodigo_pedido(codigoPedido);
                    pizza.setParametrosInterno(codigoPedido);
                    
                    if (Controlador.salvar_ItemPizzaPedido(pizza)) {
                        System.out.println("Inseriu a pizza");
                        np.atualizaTabela();
                        this.setVisible(false);
                    }   
                }else{
                    pizza.setCodigo_pizza_pedido(codPizzaPedido);
                    pizza.setParametrosInterno(codigoPedido);
                    if (Controlador.editar_ItemPizzaPedido(pizza)) {
                        System.out.println("Editou a pizza");
                        np.atualizaTabela();
                        this.setVisible(false);
                    }   
                }
                
            } else {
                throw new Exception("Adicione pelo menos um Sabor a Pizza!");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jconcluirBActionPerformed

    public boolean ValidarTamanhoSaboresPizza(String tamanho) {
        
        for (int i = 0; i < pizza.getSabores().size(); i++) {
            if (pizza.getSabores() != null && pizza.getSabores().get(i).getCategoria() != null) {
                if (!tamanho.equalsIgnoreCase(pizza.getSabores().get(i).getCategoria().getTamanho())) {
                    return false;
                }
            }
        }
        return true;
    }
    private void jpequenaRBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jpequenaRBActionPerformed
        // Caixa de seleçao Tamanho Pequena
        //if (ValidarTamanhoSaboresPizza("Pequena")) {
            jpequenaRB.setSelected(true);
            jmediaRB.setSelected(false);
            jgrandeRB.setSelected(false);
            jgiganteRB.setSelected(false);
            jsaboresRestantesTF.setText("1");
            numSabRestantes = 1;

            List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);
            filters.add(RowFilter.regexFilter("Pequena", 5));
            sorter.setRowFilter(RowFilter.andFilter(filters));
            jtabelaSaboresDisp.setRowSorter(sorter);
        //}

    }//GEN-LAST:event_jpequenaRBActionPerformed

    private void jmediaRBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmediaRBActionPerformed
        // Caixa de seleçao Tamanho Media
        //if (ValidarTamanhoSaboresPizza("Media")) {
            jpequenaRB.setSelected(false);
            jmediaRB.setSelected(true);
            jgrandeRB.setSelected(false);
            jgiganteRB.setSelected(false);
            jsaboresRestantesTF.setText("2");
            numSabRestantes = 2;

            List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);
            filtro1 = RowFilter.regexFilter("Media", 5);
            filters.add(filtro1);
            sorter.setRowFilter(RowFilter.andFilter(filters));
            jtabelaSaboresDisp.setRowSorter(sorter);
        //}
    }//GEN-LAST:event_jmediaRBActionPerformed

    private void jgrandeRBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jgrandeRBActionPerformed
        // Caixa de seleçao Tamanho Grande
        //if (ValidarTamanhoSaboresPizza("Grande")) {
            jpequenaRB.setSelected(false);
            jmediaRB.setSelected(false);
            jgrandeRB.setSelected(true);
            jgiganteRB.setSelected(false);
            jsaboresRestantesTF.setText("3");
            numSabRestantes = 3;

            List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);
            filtro1 = RowFilter.regexFilter("Grande", 5);
            filters.add(filtro1);
            sorter.setRowFilter(RowFilter.andFilter(filters));
            jtabelaSaboresDisp.setRowSorter(sorter);
       // }
    }//GEN-LAST:event_jgrandeRBActionPerformed

    private void jgiganteRBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jgiganteRBActionPerformed
        // Caixa de seleçao Tamanho Gigante
        //if (ValidarTamanhoSaboresPizza("Gigante")) {
            jpequenaRB.setSelected(false);
            jmediaRB.setSelected(false);
            jgrandeRB.setSelected(false);
            jgiganteRB.setSelected(true);
            jsaboresRestantesTF.setText("4");
            numSabRestantes = 4;

            List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);
            filters.add(RowFilter.regexFilter("Gigante", 5));
            sorter.setRowFilter(RowFilter.andFilter(filters));
            jtabelaSaboresDisp.setRowSorter(sorter);
        //}
    }//GEN-LAST:event_jgiganteRBActionPerformed

    private void jcancelarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcancelarBActionPerformed
        // Botão Cancelar
        this.setVisible(false);
    }//GEN-LAST:event_jcancelarBActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditarPizza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditarPizza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditarPizza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditarPizza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new EditarPizza().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JButton jadicionarSaborB;
    private javax.swing.JButton jcancelarB;
    private javax.swing.JButton jconcluirB;
    private javax.swing.JTextField jfiltroTF;
    private javax.swing.JRadioButton jgiganteRB;
    private javax.swing.JRadioButton jgrandeRB;
    private javax.swing.JRadioButton jmediaRB;
    private javax.swing.JRadioButton jpequenaRB;
    private javax.swing.JButton jremoverSaborB;
    private javax.swing.JTextField jsaboresRestantesTF;
    private javax.swing.JTable jtabelaPizzaPedido;
    private javax.swing.JTable jtabelaSaboresDisp;
    private javax.swing.JTextField jvalorTF;
    // End of variables declaration//GEN-END:variables
}
